package com.syedu.day11.homework;

import com.syedu.util.InputUtil;

/**
 * 分别在控制台输入字符串和子字符串，并计算字符串中子字符串出现的次数
 */
public class Exercise5 {
    public static void main(String[] args) {
        Exercise5 exercise5 = new Exercise5();
        String srcStr = InputUtil.getStrLine("请您输入原始字符串:");
        String targetStr = InputUtil.getStrLine("请您输入目标字符串:");
        int count = exercise5.getCount(srcStr, targetStr);
        System.out.println(targetStr + ",在" + srcStr + "中出现的次数为: " + count);
    }

    /**
     * 判断字符串中指定字符串出现的次数
     * @param srcStr        原字符串
     * @param targetStr     查找的目标字符串
     * @return 目标字符串在原字符串中出现的次数
     */
    public int getCount(String srcStr, String targetStr) {
        //return StringUtils.countMatches(srcStr,targetStr);

        int count = 0;
        for (int i = 0; i <= srcStr.length() - targetStr.length(); i++) {
            //if (srcStr.substring(i, i + targetStr.length()).equals(targetStr)) {
            if (srcStr.startsWith(targetStr, i)) {
                count++;
            }
        }
        return count;
    }
}